<template>
  <transition name="v-toast-fade">
    <div
      class="v-toast"
      :class="customClass"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer">
      <div class="v-toast__group" :class="{'with-closebtn': showClose}">
        <i class="v-toast__icon" :class="iconClass"></i>
        <slot><p>{{ message }}</p></slot>
        <div v-if="showClose" class="v-toast__closeBtn v-icon-close" @click="close"></div>
      </div>
    </div>
  </transition>
</template>

<script>
  const ICON_TYPES = {
    success: 'check',
    info: 'info',
    warning: 'warning',
    error: 'error',
  };
  export default {
    name: 'VToast',
    data() {
      return {
        visible: false,
        message: '',
        duration: 2500,
        type: 'info',
        customClass: '',
        onClose: null,
        showClose: false,
        closed: false,
        timer: null,
      };
    },
    computed: {
      iconClass() {
        return ICON_TYPES[this.type] ? `v-icon-${ICON_TYPES[this.type]}` : 'v-icon-info';
      },
    },
    watch: {
      closed(newVal) {
        if (newVal) {
          this.visible = false;
          this.$el.addEventListener('transitionend', this.destroyElement);
        }
      },
    },
    methods: {
      destroyElement() {
        this.$el.removeEventListener('transitionend', this.destroyElement);
        this.$destroy(true);
        this.$el.parentNode.removeChild(this.$el);
      },
      close() {
        this.closed = true;
        if (typeof this.onClose === 'function') {
          this.onClose(this);
        }
      },
      clearTimer() {
        clearTimeout(this.timer);
      },
      startTimer() {
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            if (!this.closed) {
              this.close();
            }
          }, this.duration);
        }
      },
    },
    mounted() {
      this.startTimer();
    },
  };
</script>
